<?php declare(strict_types=1);

/**
 * @author      guosir
 * @copyright   2023-2025 owner
 **/

namespace Srv\Apps\Apis\Promotion\Ctl;

use Srv\Apps\Apis\User\Ctl\UserCtl;
use Srv\Apps\Proto\DTO\Promotion\WappConvertListDTO;
use Srv\Apps\Proto\VO\Promotion\WappConvertListVO;
use Srv\Apps\Proto\VO\Promotion\WappConvertVO;
use Srv\Libs\Common\CommArray;
use Srv\Libs\Frame\ControllerAbstract;
use Srv\Libs\Frame\Page;
use Srv\Libs\Storage\DataMysql;

final class WappConvertCtl extends ControllerAbstract
{
    private ?DataMysql $DbAuto              = null;     // DB-Write



    /**
     * @return static
     * tag
     */
    final public static function tag():self
    {
        $thisObject                         = self::tagGet();
        if($thisObject instanceof self){
            $thisObject->DbAuto             = self::getDbAuto();
        }
        return $thisObject;
    }

    /**
     * @param int $wacrId
     * @return array
     * getWappConvertSrc
     */
    public function getWappConvertSrc(int $wacrId):array
    {
        if($wacrId < 1) return [];
        $isFail     = false;
        $info       = $this->DbAuto->getDataOne('SELECT wacr_id, warr_id, walr_id, dup_id, user_id, wacr_event_type, wacr_timestamp, wacr_event_data, wacr_match_type, wacr_rsp_time, wacr_rsp_body, wacr_create_time FROM '.$this->DbAuto->getTableNameAll('wapp_convert_record').' WHERE wacr_id='.$wacrId, $isFail);
        if($isFail || !isset($info['wacr_id'])) return [];
        return $info;
    }

    /**
     * @param Page $Page
     * @param array $whereData
     * @return WappConvertListVO|null
     * getWappConvertList
     */
    public function getWappConvertList(Page $Page, array $whereData): ?WappConvertListVO
    {
        $limitString            = $Page->getLimitString();
        $whereString            = ' WHERE 1 ';
        // 检索条件
        if(count($whereData) > 0)foreach ($whereData as $key => $val){
            switch ($key){
                case WappConvertListDTO::_wacrId:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'wacr_id='. intval($val);
                    break;
                case WappConvertListDTO::_warrId:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'warr_id='. intval($val);
                    break;
                case WappConvertListDTO::_walrId:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'walr_id='. intval($val);
                    break;
                case WappConvertListDTO::_dupId:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'dup_id='. intval($val);
                    break;
                case WappConvertListDTO::_eventType:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'wacr_event_type LIKE \'%'.$this->DbAuto->getRealEscapeString($val).'%\'';
                    break;
                case WappConvertListDTO::_idNum:
                    if(strlen($val) > 10 && is_numeric($val)){
                        $whereString    .= (strlen($whereString)>0?' AND ':'').'user_id='. intval($val);
                    }else{
                        $tempSql        = 'SELECT user_id FROM '.$this->DbAuto->getTableNameAll('user_info').' WHERE usi_delete=0 AND usi_idnum LIKE \'%'.$this->DbAuto->getRealEscapeString($val).'%\'';
                        $whereString    .= (strlen($whereString)>0?' AND ':'').'user_id IN('. $tempSql .')';
                    }
                    break;
                case WappConvertListDTO::_userId:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'user_id='. intval($val);
                    break;
                case WappConvertListDTO::_timestampStart:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'wacr_timestamp>='. intval($val);
                    break;
                case WappConvertListDTO::_timestampStop:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'wacr_timestamp<='. intval($val);
                    break;
                case WappConvertListDTO::_rspTimeStart:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'wacr_rsp_time>='. intval($val);
                    break;
                case WappConvertListDTO::_rspTimeStop:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'wacr_rsp_time<='. intval($val);
                    break;
                case WappConvertListDTO::_eventRspStatus:
                    $whereString        .= (strlen($whereString)>0?' AND ':'').'JSON_EXTRACT(JSON_UNQUOTE(JSON_EXTRACT(wacr_rsp_body, \'$.body\')), \'$.events_received\')='. intval($val);
                    break;
            }
        }
        $isFail                 = false;
        $sql                    = 'SELECT SQL_CALC_FOUND_ROWS wacr_id, warr_id, walr_id, dup_id, user_id, wacr_event_type, wacr_timestamp, wacr_event_data, wacr_match_type, wacr_rsp_time, wacr_rsp_body, wacr_create_time FROM '.$this->DbAuto->getTableNameAll('wapp_convert_record').$whereString.' ORDER BY wacr_id DESC '.$limitString;
        $list                   = $this->DbAuto->getData($sql, $isFail);
        $totalNum               = $this->DbAuto->getDataInt('SELECT FOUND_ROWS() as num', 'num');
        if($isFail) return null;
        $WappConvertVOList      = [];
        if(CommArray::isForeach($list)){
            $userIdList                 = array_map('intval', array_unique(array_column($list, 'user_id')));
            $UserInfoBasicVOList        = UserCtl::tag()->getUserInfoBasicBatch($userIdList);
            foreach($list as $info){
                $wacrIdItem             = intval($info['wacr_id']??0);
                if($wacrIdItem < 1) continue;
                $WappConvertVO          = $this->getWappConvertVO($info);
                if(!($WappConvertVO instanceof WappConvertVO)) continue;
                $WappConvertVO->setUserInfoBasic($UserInfoBasicVOList[intval($info['user_id'])]);
                $WappConvertVOList[]    = $WappConvertVO;
            }
        }
        $WappConvertListVO              = new WappConvertListVO();
        $WappConvertListVO->setList($WappConvertVOList);
        $WappConvertListVO->setPage($Page->getPageVO($totalNum));
        return $WappConvertListVO;
    }

    /**
     * @param int $wacrId
     * @return WappConvertVO|null
     * getWappConvertInfo
     */
    public function getWappConvertInfo(int $wacrId):?WappConvertVO
    {
        $infoSrc    = $this->getWappConvertSrc($wacrId);
        if(!isset($infoSrc['wacr_id'])) return null;
        return $this->getWappConvertVO($infoSrc);
    }

    /**
     * @param array $info
     * @return WappConvertVO|null
     * getWappConvertVO
     */
    public function getWappConvertVO(array $info):?WappConvertVO
    {
        $wacrId             = intval($info['wacr_id']??0);
        if($wacrId < 1) return null;
        $WappConvertVO      = new WappConvertVO();
        $WappConvertVO->setWacrId($wacrId);
        $WappConvertVO->setWarrId(intval($info['warr_id']));
        $WappConvertVO->setWalrId(intval($info['walr_id']));
        $WappConvertVO->setDupId(intval($info['dup_id']));
        $WappConvertVO->setEventType(trim($info['wacr_event_type']));
        $WappConvertVO->setTimestamp(intval($info['wacr_timestamp']));
        $WappConvertVO->setEventData(trim($info['wacr_event_data']));
        $WappConvertVO->setMatchType(trim($info['wacr_match_type']));
        $WappConvertVO->setRspTime(intval($info['wacr_rsp_time']));
        $WappConvertVO->setRspBody(trim($info['wacr_rsp_body']));
        $WappConvertVO->setCreateTime(intval($info['wacr_create_time']));
        return $WappConvertVO;
    }
}